# -*- coding: utf-8 -*-
# @Time    : 2021/8/14 12:56
# @Author  : Flora.Chen
# @File    : baseapi.py
# @Software: PyCharm
# @Desc:
import requests
from loguru import logger
import urllib3
from urllib3.exceptions import InsecureRequestWarning

# 加这句不会报错(requests证书警告)
urllib3.disable_warnings(InsecureRequestWarning)


class BaseApi(object):
    """
    BaseApi作为所有单接口的父类出现，将所有接口公共的属性或者方法信息进行抽象封装
    """
    session = None

    def __init__(self):
        self.url = None
        self.method = None
        self.headers = None
        self.data = None
        self.params = None
        self.json = None
        self.response = None

    @classmethod
    def get_session(cls):
        """
        单例模式保证测试过程中使用的都是一个session对象
        :return:
        """
        if cls.session is None:
            cls.session = requests.Session()
        return cls.session

    def send_api(self, **kwargs):
        session = self.get_session()
        return session.request(**kwargs)

    def send_request(self, **kwargs):
        """
        发送请求
        :param kwargs: 表示接口在发起时有一些自定义的参数或者其他的数据
        :return:
        """
        # if处理表示的是调用方如果不传递某些参数，那么就用当前对象自己的属性
        if kwargs.get("method") is None:
            kwargs["method"] = self.method
        if kwargs.get("url") is None:
            kwargs["url"] = self.url
        if kwargs.get("params") is None:
            kwargs["params"] = self.params
        if kwargs.get("data") is None:
            kwargs["data"] = self.data
        if kwargs.get("json") is None:
            kwargs["json"] = self.json
        if kwargs.get("headers") is None:
            kwargs["headers"] = self.headers
        logger.debug("----------- 开始发送请求 -----------\n")
        logger.debug(f"----------- 请求参数：{kwargs} -----------\n")
        response = self.send_api(**kwargs)
        if response.status_code // 100 == 2:
            logger.debug(f"----------- 响应码200-299返回的响应数据(text)：{response.text} -----------\n")
        else:
            logger.debug(f"----------- 响应码不是200-299返回的响应数据：{response.text} -----------\n")
        logger.debug("----------- 结束发送请求 -----------\n")
        return response
